package com.rzico.basics.service;

import com.google.common.collect.Lists;
import com.rzico.base.BaseMapper;
import com.rzico.base.impl.BaseServiceImpl;
import com.rzico.basics.entity.Member;
import com.rzico.basics.entity.Turntable;
import com.rzico.basics.entity.TurntablePrize;
import com.rzico.basics.entity.TurntableRecord;
import com.rzico.basics.mapper.TurntableMapper;
import com.rzico.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <pre>
 * 大转盘业务类
 * </pre>
 *
 * @author Rzico Boot
 * @version 1.0
 */
@Service
public class TurntableService extends BaseServiceImpl<Turntable, String> {

    @Autowired
    private TurntableMapper turntableMapper;

    @Autowired
    private TurntablePrizeService turntablePrizeService;

    @Autowired
    private TurntableRecordService turntableRecordService;

    @Override
    public BaseMapper<Turntable, String> getMapper() {
        return turntableMapper;
    }

    /**
     * 新增大转盘
     */
    @Transactional(rollbackFor = Exception.class)
    public Turntable save(Turntable turntable) {
        turntable.setDeleted(false);
        super.insertUseGeneratedKeys(turntable);
        if (turntable.getId() != null) {
            addPrize(turntable.getPrizeList(), turntable.getId());
        }
        return turntable;
    }

    /**
     * 更新大转盘
     */
    @Transactional(rollbackFor = Exception.class)
    public Turntable update(Turntable turntable) {
        super.updateByPrimaryKeySelective(turntable);
        Long turntableId = turntable.getId();

        List<TurntablePrize> addPrizes = new ArrayList<>();
        List<TurntablePrize> editPrizes = new ArrayList<>();

        for (TurntablePrize prize : turntable.getPrizeList()) {
            if (prize.getId() != null){
                editPrizes.add(prize);
                continue;
            }
            addPrizes.add(prize);
        }

        List<Long> editIds = editPrizes.stream().map(TurntablePrize::getId).collect(Collectors.toList());
        turntablePrizeService.deleteByTurntableId(turntable.getId(), editIds);

        addPrize(addPrizes, turntableId);

        if (editPrizes.size() > 0) {
            int size = addPrizes.size();
            for (TurntablePrize prize : editPrizes) {
                prize.setTurntableId(turntable.getId());
                prize.setSort(++size);
            }
        }
        return turntable;
    }

    /**
     * 新增奖品
     *
     * @param prizeList   奖品集合
     * @param turntableId 大转盘ID
     */
    @Transactional(rollbackFor = Exception.class)
    public void addPrize(List<TurntablePrize> prizeList, Long turntableId) {
        if (prizeList != null && prizeList.size() > 0) {
            int i = 1;
            for (TurntablePrize prize : prizeList) {
                prize.setTurntableId(turntableId);
                prize.setSort(i++);
            }
            turntablePrizeService.insertList(prizeList);
        }
    }

    /**
     * 参加大转盘进行抽奖
     *
     * @param turntable
     * @param member
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public synchronized TurntableRecord attendTurntable(Turntable turntable, Member member) throws Exception {
        TurntableRecord record = turntableRecordService.findByisDraw(turntable.getId(), member.getId());
        List<TurntablePrize> prizeList = turntable.getPrizeList();
        if (record != null) {
            TurntablePrize prize = turntablePrizeService.findById(record.getPrizeId());
            if (prize != null) {
                record.setPrizeName(prize.getPrizeName());
                for (int i = 0; i < prizeList.size(); i++) {
                    TurntablePrize turntablePrize = prizeList.get(i);
                    if (turntablePrize.getId().equals(record.getPrizeId())) {
                        BigDecimal eachAngle = new BigDecimal(360).divide(new BigDecimal(prizeList.size()), 3, BigDecimal.ROUND_HALF_UP);
                        record.setAngle(eachAngle.multiply(new BigDecimal(i)).add(eachAngle.divide(new BigDecimal(2), 3, BigDecimal.ROUND_HALF_UP)));
                        record.setScratchTime(new Date());
                        record.setScratchTimeInt(Integer.valueOf(DateUtils.getDateStr(new Date(), 1)));
                        turntableRecordService.updateByPrimaryKey(record);
                        return record;
                    }
                }
            }
            turntableRecordService.delete(record);
        }

        // 剩余最多参与次数

        int limit = 0;

        List<Integer> count = new ArrayList<>();
        for (TurntablePrize prize : prizeList) {
            int i = limit;
            if (prize.getPrizeRemain() > 0) {
                limit += prize.getPrizeRemain();
            }
            if (limit > i) {
                count.add(limit);
            } else {
                count.add(0);
            }
        }
        if(limit<=0){
            throw new Exception("活动奖项已抽完！");
        }

//        Integer oriAttendRemain = turntable.getAttendRemain();
        turntable.setAttendRemain(limit - 1);
        super.updateByPrimaryKey(turntable);
        // 随机数.
        int random = (int) Math.round(Math.random() * (limit - 1) + 1);

        record = new TurntableRecord();
        record.setTurntableId(turntable.getId());
        record.setMemberId(member.getId());
        record.setScratchTime(new Date());
        record.setScratchTimeInt(Integer.valueOf(DateUtils.getDateStr(new Date(), 1)));
        record.setIsDraw(0);
        record.setIsUsed(0);

        for (int i = 0, length = count.size(); i < length; i++) {
            if (random <= count.get(i)) {
                TurntablePrize prize = prizeList.get(i);
                prize.setPrizeRemain(prize.getPrizeRemain() - 1);
                turntablePrizeService.updateByPrimaryKey(prize);
                if (prize.getIsWin() == 1) {
                    record.setScratchResult(1);
                    record.setPrizeId(prize.getId());
                    record.setPrizeName(prize.getPrizeName());
                    if ("1".equals(prize.getPrizeType())) {
                        record.setResultRemark("优惠券【" + prize.getPrizeName() + "】");
                    }
                } else {
                    record.setScratchResult(0);
                    record.setResultRemark(prize.getPrizeName());
                    record.setPrizeName(prize.getPrizeName());
                }
                BigDecimal eachAngle = new BigDecimal(360).divide(new BigDecimal(length), 3, BigDecimal.ROUND_HALF_UP);
                record.setAngle(eachAngle.multiply(new BigDecimal(i)).add(eachAngle.divide(new BigDecimal(2), 3, BigDecimal.ROUND_HALF_UP)));
                break;
            }
        }

        turntableRecordService.insertUseGeneratedKeys(record);
        return record;
    }

    /**
     * 批量删除 大转盘活动  - 进行假删除操作
     */
    public int delByIds(String[] ids) {
        return turntableMapper.delByIds(Lists.newArrayList(ids));
    }

}
